package com.ruoyi.ruoyiqywechat.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.qy.exception.CrmebException;
import com.ruoyi.common.qy.utils.PythonCaller;
import com.ruoyi.common.qy.vo.DouYinVideoVo;
import com.ruoyi.common.qy.vo.XiaoHongShuVideoVo;
import com.ruoyi.common.redis.utils.RedisUtil;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.ruoyiqywechat.domain.UserMembership;
import com.ruoyi.ruoyiqywechat.service.IUserMembershipService;
import com.ruoyi.ruoyiqywechat.service.XiaoHongShuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
public class XiaoHongShuServiceImpl implements XiaoHongShuService {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IUserMembershipService userMembershipService;


    @Async
    @Override
    public void extractAudioFromVideo(String userId, String s, String videoId) {
         String xiaoHongShuVideoUrl = PythonCaller.getXiaoHongShuVideoUrl(s);
        System.out.println("最终获取到小红书无水印视频地址："+xiaoHongShuVideoUrl);
        XiaoHongShuVideoVo xiaoHongShuVideoVo = XiaoHongShuVideoVo.getInstance();
        xiaoHongShuVideoVo.setVideoId(videoId);
        xiaoHongShuVideoVo.setUrl(xiaoHongShuVideoUrl);
        xiaoHongShuVideoVo.setExtracting(false);
        xiaoHongShuVideoVo.setExtractProgress(100);
        xiaoHongShuVideoVo.setExtractStep(3);
        xiaoHongShuVideoVo.setExtractStatus("小红书提取成功!");
        xiaoHongShuVideoVo.setOldUrl(s);
        redisUtil.hset(CacheConstants.XIAOHONGSHU_CREATE_HASH +userId,videoId, JSONObject.toJSONString(xiaoHongShuVideoVo));//hash存视频的详情信息,已完成
    }

    @Override
    public Object listDouYinVideoById(HttpServletRequest request, String videoId) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isBlank(token)) {
            throw new CrmebException("请先登录!");
        }
        String userId = JwtUtils.getUserId(token);
        Object hgetted = redisUtil.hget(CacheConstants.XIAOHONGSHU_CREATE + userId, videoId);
        return hgetted;
    }

    @Override
    public List<XiaoHongShuVideoVo> listDouYinVideoByUserId(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isBlank(token)) {
            throw new CrmebException("请先登录!");
        }
        String userId = JwtUtils.getUserId(token);
        List<Object> objectList = redisUtil.lGet(CacheConstants.XIAOHONGSHU_CREATE + userId, 0, -1);
        ArrayList<XiaoHongShuVideoVo> douYinVideoVoArrayList = new ArrayList<>();
        for (Object o : objectList) {
            Object hget = redisUtil.hget(CacheConstants.XIAOHONGSHU_CREATE_HASH + userId, (String) o);
            // 直接解析从 Redis 获取的字符串
            if (hget != null) {
                XiaoHongShuVideoVo xiaoHongShuVideoVo = JSONObject.parseObject((String) hget, XiaoHongShuVideoVo.class);

                    xiaoHongShuVideoVo.setExtractProgress(xiaoHongShuVideoVo.getExtractProgress()+5);
                    if(xiaoHongShuVideoVo.getExtractProgress()>=50 && xiaoHongShuVideoVo.getExtractProgress()<100){
                        xiaoHongShuVideoVo.setExtractStep(1);
                    }else if(xiaoHongShuVideoVo.getExtractProgress() >= 100){
                        xiaoHongShuVideoVo.setExtractProgress(100);
                        xiaoHongShuVideoVo.setExtractStep(2);
                    }
                    douYinVideoVoArrayList.add(xiaoHongShuVideoVo);
                    redisUtil.hset(CacheConstants.XIAOHONGSHU_CREATE_HASH + userId,xiaoHongShuVideoVo.getVideoId(),JSONObject.toJSONString(xiaoHongShuVideoVo));
            }
        }
        return douYinVideoVoArrayList;
    }

    @Override
    public Boolean queryWatchVideoNum(HttpServletRequest request, String videoId) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isBlank(token)) {
            throw new CrmebException("请先登录!");
        }
        String userId = JwtUtils.getUserId(token);
        // 使用当天日期作为key的一部分，确保每天自动刷新
        String cacheKey = CacheConstants.WATCH_VIDEO_XIAO_HONG_SHU_NUM + userId ;
        Long watchCount = redisUtil.incr(cacheKey, 1L);
        Long decr = redisUtil.decr(cacheKey, 1L);
        System.out.println("用户："+userId+videoId+"观看次数"+decr);
        //判断当前是否是会员
        //判断当前会员是否重复，如果是则不允许重复会员充值
        QueryWrapper<UserMembership> userMembershipQueryWrapper = new QueryWrapper<>();
        userMembershipQueryWrapper.lambda().eq(UserMembership::getUserId,userId)
                .eq(UserMembership::getStatus,1);
        UserMembership one = userMembershipService.getOne(userMembershipQueryWrapper);
        if(one != null){
            return false;
        }

        return decr <= 1;
    }

    @Override
    public void addWatchVideoNum(HttpServletRequest request, String videoId) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isBlank(token)) {
            throw new CrmebException("请先登录!");
        }
        String userId = JwtUtils.getUserId(token);
        String cacheKey = CacheConstants.WATCH_VIDEO_XIAO_HONG_SHU_NUM + userId ;
        redisUtil.incr(cacheKey, 1L);
    }
}
